/**
 * Project Name:kany-utils
 * File Name:Option.java
 * Package Name:me.kany.utils.config.ini
 * Date:2016-1-7上午11:10:35
 * Copyright (c) 2016, Jason.Wang All Rights Reserved.
 *
 */

package me.kany.utils.config.ini.option;

import java.util.StringTokenizer;

import me.kany.utils.config.ini.line.Line;

/**
 * ClassName:Option <br/>
 * Function: INI文件的选项. <br/>
 * Date: 2016-1-7 上午11:10:35 <br/>
 * 
 * @author Jason.Wang
 * @version
 * @since JDK 1.7
 * @see
 */
public class Option implements Line {

	private String name;
	private String value;
	private char separator;
	private OptionFormat format;

	private static final String ILLEGAL_VALUE_CHARS = "\n\r";

	public Option(String name, String value, char separator, OptionFormat format) {
		if (!validName(name, separator)) {
			throw new IllegalArgumentException("Illegal option name:" + name);
		}
		this.name = name;
		this.separator = separator;
		this.format = format;
		set(value);
	}

	public String name() {
		return this.name;
	}

	public String value() {
		return this.value;
	}

	public void set(String value) {
		if (value == null) {
			this.value = value;
		} else {
			StringTokenizer st = new StringTokenizer(value.trim(), ILLEGAL_VALUE_CHARS);
			StringBuffer sb = new StringBuffer();
			while (st.hasMoreTokens()) {
				sb.append(st.nextToken());
			}
			this.value = sb.toString();
		}
	}

	public String toString() {
		return this.format.format(this.name, this.value, this.separator);
	}

	private static boolean validName(String name, char separator) {
		if (name.trim().equals("")) {
			return false;
		}
		if (name.indexOf(separator) >= 0) {
			return false;
		}
		return true;
	}

}
